package org.ekstrabilet.search.gui;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;

/**  
 * Class provides component which is used to choose Date with The use of Comboboxes
 * implements methods which returns date for sql-searching and printing
 */
public class DateChooser {
	
	private JComboBox dayCB;    
	private JComboBox monthCB;
	private JComboBox yearCB;
	private Integer[] monthLength = {31,28,31,30,31,30,31,31,30,31,30,31};
	private Integer[] months = {1,2,3,4,5,6,7,8,9,10,11,12};
	private Integer[] days;
	private Integer[] years;
	
	
	
	public DateChooser(){
		days = new Integer[31];
		years = new Integer[1000];
		for (int i=1; i<=31; ++i){
			days[i-1]=i;
		}
		for (int i=0; i<1000;++i){
			years[i]=1990+i;
		}
		monthCB = new JComboBox(months);
		dayCB = new JComboBox(days);		
		yearCB = new JComboBox(years);
		
		monthCB.addActionListener(
	            new ActionListener() {
	                public void actionPerformed(ActionEvent e) {                		
	                	       	
	                    if((Integer)dayCB.getSelectedItem() > monthLength[(Integer)monthCB.getSelectedItem()-1]){
	                    	dayCB.setSelectedItem(monthLength[(Integer)monthCB.getSelectedItem()-1]);
	                    }
	                    
	                }
	            }
	        );
		dayCB.addActionListener(
	            new ActionListener() {
	                public void actionPerformed(ActionEvent e) {                		
	                	       	
	                    if((Integer)dayCB.getSelectedItem() > monthLength[(Integer)monthCB.getSelectedItem()-1]){
	                    	dayCB.setSelectedItem(monthLength[(Integer)monthCB.getSelectedItem()-1]);
	                    }
	                    
	                }
	            }
	        );

	}
	
	/**  
	 * Returns DateChooser component 
	 */
	public Box getDateChooser() {
		Box dateChooser = Box.createHorizontalBox();
		dateChooser.add(dayCB);
		dateChooser.add(monthCB);
		dateChooser.add(yearCB);
		
		return dateChooser;		
	}

	/**  
	 * Returns Date from DateChooser in String format
	 */
	public String getDate(){
		return (yearCB.getSelectedItem().toString() + "-" + monthCB.getSelectedItem().toString() + "-" + dayCB.getSelectedItem().toString() );		
	}
	
	/**  
	 * Returns Date from DateChooser in sql-style
	 */
	public Date getSqlDate() {
		int y = (Integer) yearCB.getSelectedItem() - 1900; //retarded hack xD
		int m = (Integer) monthCB.getSelectedItem() - 1; //as higher
		int d = (Integer) dayCB.getSelectedItem();
		return new Date(y, m, d);
	}

}
